package com.jswj.media.task;

import com.jswj.media.task.abs.AbstractScreenshot;
import com.jswj.screenshot.domain.Screenshot;
import com.jswj.screenshot.service.IScreenshotService;
import com.jswj.word.domain.WordExt;
import com.jswj.word.service.IWordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author wanghonghui
 * @Description TODO
 * @Date 2021/7/6 下午6:22
 */
@Slf4j
@Component("screenshotTask")
public class ScreenshotTask extends AbstractScreenshot {

    @Autowired
    IWordService wordService;

    @Autowired
    IScreenshotService screenshotService;


    // 0 */1 * * * ?
    // 每隔一分钟执行一次
    public void st() {

        WebDriver driver = getDriver();
        try {
            driver.manage().window().setSize(new Dimension(1500, 900));
            List<WordExt> wordExtList = wordService.selectWordList(null);
            takeScreenshot(driver, wordExtList);
        } catch(Exception ex) {
            ex.printStackTrace();
        } finally {
            driver.quit();
        }
    }

    /**
     * 截图
     *
     * @param webDriver
     * @param words
     * @return
     * @throws Exception
     */
    @Override
    public void takeScreenshot(WebDriver webDriver, List<WordExt> words) {
        Actions actions = new Actions(webDriver);
        //休眠5秒，等待广告页自动关闭
        //Thread.sleep(5000);
        //遍历关键词
        words.forEach(word -> {
            String keyWords = word.getWords();
            word.getMediaList().forEach(media -> {
                Screenshot screenshot;
                webDriver.get(media.getUrl());
                //等待10秒后继续
                webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//                WebDriverWait webDriverWait = new WebDriverWait(webDriver, 10);
//                webDriverWait.until(new ExpectedCondition<WebElement>() {
//                    @NullableDecl
//                    @Override
//                    public WebElement apply(@NullableDecl WebDriver webDriver) {
//                        return null;
//                    }
//                });

                //关闭广告页
                try {
                    webDriver.findElement(By.xpath("//div[@id='tmadvClose']")).click();
                    webDriver.findElement(By.xpath("//div[@id='fcadvClose']")).click();
                } catch(Exception e){
                    log.info("没有广告页");
                }

                //每个关键词依次查找
                for (String keyWord : keyWords.split("@")) {
                    keyWord = keyWord.trim();
                    //获取需要截图的节点元素
                    List<WebElement> eles = webDriver.findElements(By.xpath("//a/descendant-or-self::*[contains(text(), '" + keyWord + "')]"));
                    if (CollectionUtils.isNotEmpty(eles)) {
                        log.error("找到【"+keyWord+"】共"+eles.size()+"处");
                        for (WebElement ele : eles) {
                            //计算是否是滚动div，如果是计算是否需要点击，如果是，自动点击
                            handleCarousel(webDriver, ele, actions);
                            try {
                                //获得webElement的位置和大小，元素被隐藏后大小是0，有bug。
//                            Dimension size = ele.getSize();
//                            if (size.height > 0 && size.width > 0) {
                                String uuid = UUID.randomUUID().toString();
                                setStyle(webDriver, ele);
                                setScrollElementToMiddle(webDriver, ele);
                                File imgFile = takeScreenshotToFile(webDriver);
                                try {
                                    FileUtils.copyFile(imgFile, new File(IMG_PATH + uuid + ".png"));
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                try {
                                    System.err.println(ele.getText());
                                    screenshot = new Screenshot();
                                    screenshot.setMedia(media.getMediaName());
                                    screenshot.setPosition(null);
                                    screenshot.setTitle(ele.getText().replaceAll("[\r\n]", ""));
                                    screenshot.setLink(ele.getAttribute("href"));
                                    screenshot.setAddTime(new Date());
                                    screenshot.setImg(uuid + ".png");
                                    screenshot.setWordId(word.getId());
                                    screenshotService.insertScreenshot(screenshot);
                                } catch (Exception e) {
                                    log.error(e.getMessage());
                                }
                                //System.err.println("--" + ele.getText().replaceAll("[\r\n]", ""));
//                            } else {
//                                log.warn("元素大小是0，重新计算");
//                            }
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    }else{
                        log.warn("未找到关键词："+keyWord);
                    }
                }
            });
        });
    }
}
